/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ru.miit.elearning.vtutor.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONObject;
import ru.miit.elearning.vtutor.check.CheckObjectDetail;
import ru.miit.elearning.vtutor.check.Combination;
import ru.miit.elearning.vtutor.data.CheckObjectType;
import ru.miit.elearning.vtutor.data.DataMiner;

/**
 *
 * @author Cyclone
 */
public class WorkDetailsServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        DataMiner miner = null;
        try {

            int studentId = Integer.parseInt(request.getParameter("studentId"));
            int labNumber = Integer.parseInt(request.getParameter("labNumber"));
            int courseId = Integer.parseInt(request.getParameter("courseId"));

            miner = new DataMiner();

            String details = miner.findWorkDetails(studentId, courseId, labNumber);
            if (details != null) {
                JSONObject json = new JSONObject(details);

                //Integer labNumber = json.getInt("labNumber");
                //String labTitle = json.getString("labTitle");
                //String studentName = json.getString("name");

                Integer percent = json.getInt("percent");

                JSONArray jsonCheckObjects = json.optJSONArray("checkObjects");

                List<CheckObjectDetail> coDetailsList = null;
                if (jsonCheckObjects != null && jsonCheckObjects.length() > 0) {
                    coDetailsList = new ArrayList<CheckObjectDetail>(jsonCheckObjects.length());
                    for (int i = 0; i < jsonCheckObjects.length(); i++) {
                        JSONObject jsonCheckObject = jsonCheckObjects.getJSONObject(i);

                        CheckObjectDetail coDetail = new CheckObjectDetail();
                        coDetail.setPath(jsonCheckObject.getString("path"));
                        coDetail.setType(jsonCheckObject.getInt("type"));
                        coDetail.setResult(jsonCheckObject.getInt("result"));
                        coDetail.setStatus(jsonCheckObject.getInt("status"));

                        if (jsonCheckObject.has("combs")) {
                            JSONArray jsonCombs = jsonCheckObject.getJSONArray("combs");
                            List<Combination> combList = null;
                            if (jsonCombs != null && jsonCombs.length() > 0) {
                                combList = new ArrayList<Combination>(jsonCombs.length());

                                for (int j = 0; j < jsonCombs.length(); j++) {
                                    JSONObject jsonComb = jsonCombs.getJSONObject(j);
                                    Combination comb = new Combination();

                                    comb.setComb(jsonComb.getString("comb"));
                                    Integer check = jsonComb.getInt("check");
                                    if (check != null && check.equals(0)) {
                                        comb.setChecked(true);
                                    } else {
                                        comb.setChecked(false);
                                    }

                                    combList.add(comb);
                                }
                            }
                            coDetail.setCombList(combList);
                        }

                        coDetailsList.add(coDetail);
                    }
                }

                List<CheckObjectType> coTypeList = null;
                try {
                    coTypeList = miner.getCheckObjectTypeList();
                } catch (Exception e) {
                    Logger.getLogger(LabTaskServlet.class.getName()).log(Level.SEVERE, null, e);
                    e.printStackTrace();
                }
                if (coTypeList != null) {
                    request.setAttribute("coTypeList", coTypeList);
                }

                request.setAttribute("coDetailsList", coDetailsList);
                request.setAttribute("percent", percent);
            }

            request.setAttribute("studentId", studentId);
            request.setAttribute("courseId", courseId);
            request.setAttribute("labNumber", labNumber);



            //request.setAttribute("details", details.replaceAll("\\n", "<br/>"));
            getServletContext().getRequestDispatcher("/workdetails.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            Logger.getLogger(WorkDetailsServlet.class.getName()).log(Level.SEVERE, null, e);
            out.print("Произошла ошибка запроса деталей выполнения практической работы.<br/>");
            out.print("Пожалуйста, обратитесь к администратору.");
        } finally {
            if (miner != null) {
                miner.close();
            }
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
